using System;

namespace Framework
{
    public class ResManager : Singleton<ResManager>
    {
        public ResLoader Load(string url, Action<Resource> onCompleted)
        {
            return Load(url, onCompleted, ResLoadType.Async);
        }
        
        public ResLoader Load(string url, Action<Resource> onCompleted,
            int loadType)
        {
            Resource resource = ResCache.Get(url, loadType);
            if (resource.isDone)
            {
                if (string.IsNullOrEmpty(resource.error))
                {
                    onCompleted(resource);
                    return null;
                }
                resource.Reset();
            }
            resource.Completed += onCompleted;
            return LoadResource(resource);
        }
        
        public void Cancel(string url, Action<Resource> onCompleted)
        {
            Resource resource = ResCache.Find(url);
            if (resource != null)
            {
                resource.Completed -= onCompleted;
                if (!resource.isDone)
                {
                    CancelLoadResource(resource);
                }
            }
        }

        public Resource GetResource(string url)
        {
            return ResCache.Find(url);
        }
        
        private ResLoader LoadResource(Resource resource)
        {
            ResLoader loader = LoaderCache.Get(resource);
            if (!loader.isLoading)
            {
                loader.Completed += OnLoaderCompleted;
                loader.Start();
            }
            return loader;
        }

        private void CancelLoadResource(Resource resource)
        {
            if (!resource.HasCompletedEvent())
            {
                ResLoader loader = LoaderCache.Find(resource);
                if (loader != null)
                {
                    loader.Cancel();
                    OnLoaderCompleted(loader);
                }
            }
        }

        private void OnLoaderCompleted(ResLoader loader)
        {
            loader.Completed -= OnLoaderCompleted;
            LoaderCache.Release(loader);
        }
    }
}